<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>运营管理</el-breadcrumb-item>
      <el-breadcrumb-item>优惠券管理</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="add">
            <el-button type="primary" @click="show = true;dialogTitle='添加优惠券'">添加优惠券</el-button>
        </div>
        <el-card>
            <el-table
                :data="productList"
                stripe
                border
                style="width: 100%">
                <el-table-column
                    prop="name"
                    label="优惠券名称">
                </el-table-column>
                <el-table-column
                    prop="desc"
                    label="优惠券描述">
                </el-table-column>
                <el-table-column
                    prop="reach"
                    label="优惠券满减金额">
                </el-table-column>
                <el-table-column
                    prop="derate"
                    label="优惠券折扣金额">
                </el-table-column>
                <el-table-column
                    prop="startTime"
                    label="优惠券开始时间">
                    <template slot-scope="scope">
                        <div>{{setDate(scope.row.startTime)}}</div>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="endTime"
                    label="优惠券结束时间">
                    <template slot-scope="scope">
                        <div>{{setDate(scope.row.endTime)}}</div>
                    </template>
                </el-table-column>
                <el-table-column
                    label="操作">
                    <template slot-scope="scope">
                        <div>
                            <el-button type="primary" @click="changeCommodity(scope.row)">修改</el-button>
                            <el-button type="danger" @click="delCommodity(scope.row)">删除</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <el-dialog :title="dialogTitle" :visible.sync="show" @close="()=>{resetForm('productForm')}">
            <el-form :model="productForm" :rules="productFormRules" ref="productForm">
                <el-form-item label="优惠券名称" prop="name">
                    <el-input v-model="productForm.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="优惠券描述" prop="desc">
                  <el-input v-model="productForm.desc" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="优惠券满减金额" prop="reach">
                    <el-input type="number" el-input v-model="productForm.reach" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="优惠券折扣金额" prop="derate">
                    <el-input type="number" el-input v-model="productForm.derate" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="优惠券使用时间区间" prop="date">
                    <el-date-picker
                      v-model="productForm.date"
                      type="datetimerange"
                      range-separator="至"
                      :picker-options="{ disabledDate: time =>  time.getTime() < Date.now()- 8.64e7 }"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="()=>{resetForm('productForm');show = false;}">取 消</el-button>
                <el-button type="primary" @click="addCommodity" :loading='loading'>确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data(){
        let validateDate = (rule, value, callback) => {
          if (this.productForm.date.length == 0) {
            return callback(new Error('请选择优惠券使用时间区间'));
          }
          callback();
        };
        return{
            typeList:[],
            loading:false,
            dialogTitle:'',
            show:false,
            productList:[],
            productForm: {
                name: "",
                desc: "", 
                reach: "", 
                derate: "" ,
                date:""
            },
            productFormRules: {
                name:[ { required: true, message: '请输入优惠券名称', trigger: 'blur' } ],
                desc:[ { required: true, message: '请输入优惠券描述', trigger: 'blur' } ],
                reach:[ { required: true, message: '请输入优惠券满减金额', trigger: 'blur' } ],
                derate:[ { required: true, message: '请输入优惠券折扣金额', trigger: 'blur' } ],
                date: [{required: true, validator: validateDate, trigger: 'blur' }]
            },
        }
    },
    async created(){
        this.getComputed()
    },
    methods:{
        async getComputed(){
            const { data } = await this.$http.get('venue/coupon')
            if (data.state !== 0) {
            return this.$message.error(data.msg)
            }
            this.productList = data.result
        },
        addCommodity(){
            this.$refs['productForm'].validate(async (valid) => {
                if(!valid) return
                let model = this.dialogTitle == '添加优惠券' ? "post" : "put"
                let params;
                let obj = JSON.stringify(this.productForm)
                params = JSON.parse(obj)
                let date = params.date
                delete params.date
                params.startTime = this.setDate(date[0]) 
                params.endTime = this.setDate(date[1]) 
                this.loading = true
                const { data } = await this.$http[model]('venue/coupon',params)
                this.loading = false
                this.show = false
                this.resetForm('productForm')
                this.getComputed()
                if (data.state !== 0) return this.$message.error(data.msg)
                return this.$message.success(this.dialogTitle == '添加优惠券' ? "添加成功" : "修改成功")
            })
        },
        changeCommodity(item){
            this.dialogTitle = "修改优惠券"
            this.show =true
            let obj = JSON.stringify(item)
            let itemInfo = JSON.parse(obj)
            itemInfo.date = [itemInfo.startTime,itemInfo.endTime]
            delete itemInfo.startTime
            delete itemInfo.endTime
            this.productForm = itemInfo
        },
        delCommodity(item){
            this.$confirm('是否删除该优惠券', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                console.log(item)
                const { data } = await this.$http.delete('venue/coupon',{data:{id:item.id}})
                this.getComputed()
                if (data.state !== 0) return this.$message.error(data.msg)
                return this.$message.success("删除成功")
            })
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        setDate(originValue) {
              const dt = new Date(originValue)
              const y = dt.getFullYear()
              // 月份，字符串不足两位以0填充
              const m = (dt.getMonth() + 1 + '').padStart(2, '0')
              const d = (dt.getDate() + '').padStart(2, '0')
              const hh = (dt.getHours() + '').padStart(2, '0')
              const mm = (dt.getMinutes() + '').padStart(2, '0')
              const ss = (dt.getSeconds() + '').padStart(2, '0')

              return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
          },
    }
}
</script>

<style scoped>
    .add{
        display: flex;
        justify-content: flex-end;
    }
    .add .el-button{
        margin-bottom: 10px;
    }
</style>